package com.keur.money.ui.market.act

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.View
import com.keur.money.R
import com.keur.money.app.MyApp
import com.keur.money.base.utils.thread.TimingThread
import com.keur.money.databinding.ActMullaApplyWaitBinding
import com.keur.money.http.HttpHelper
import com.keur.money.mvp.ProAct
import com.keur.money.utils.event.KeurEventData
import com.keur.money.utils.event.KeurEventType
import com.keur.money.utils.helper.KeurCustomConfigsHelper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/8/5 18:45
 * @Annotation：申请贷款等待
 */
class KeurApplyWaitAct: ProAct(), TimingThread.ITimingThreadListener {
    lateinit var binding: ActMullaApplyWaitBinding
    private var timeThread: TimingThread? = null
    //等待时长
    private var countdown = 9

    companion object {
        private const val INTENT_KEY_PRODUCT = "product"
        private const val INTENT_KEY_TOKEN = "token"
        fun start(context: Context, pName: String, pToken: String) {
            val intent = Intent(context, KeurApplyWaitAct::class.java)
            intent.putExtra(INTENT_KEY_PRODUCT, pName)
            intent.putExtra(INTENT_KEY_TOKEN, pToken)
            context.startActivity(intent)
        }
    }

    override fun getMullaRootView(): View {
        binding = ActMullaApplyWaitBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initMullaView() {
        setMullaTitleBarColor(Color.parseColor("#FFFFFFFF"))
        setMullaTextTitle("")
        setMullaBackBtnVisibility(View.INVISIBLE)
        setMullaRightBtnRes(R.mipmap.mulla_apply_wait_kefu)

        val textMSG = getString(R.string.apply_wait_msg)
        val showText = String.format(getString(R.string.apply_wait_tips),textMSG)

        val msgIndex = showText.indexOf(textMSG)
        val spString = SpannableString(showText)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FFFF0000")), msgIndex, msgIndex + textMSG.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spString.setSpan(StyleSpan(Typeface.BOLD), msgIndex, msgIndex + textMSG.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        binding.textWaitTips.text = spString
    }

    override fun initMullaListener() {
        //联系客服
        rootViewBinding.ivFun.setOnClickListener {
            showMullaKefuDialog("Apply Wait Preview Page",loadProductName(),loadProductToken())
            HttpHelper.addKeurEventAction(KeurEventType.CLICK.KEUR_CLICK_CUSTOMER, "Apply Wait Preview Page")
        }
    }

    override fun initMullaData() {
        startTimeThread()

        //牌照信息
        val licenseInfo = KeurCustomConfigsHelper.getMullaLicenseInfo()
        if (licenseInfo == null){
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.addView(licenseView())
            binding.licenseLayout.visibility = View.VISIBLE
        }
    }

    /**
     * 启动倒计时
     */
    private fun startTimeThread() {
        if (timeThread != null) {
            timeThread?.stopThread()
        }
        //随机 10秒 等待时长
        countdown = 9
        showMullaTipsText()
        if (timeThread == null) {
            timeThread = TimingThread()
            timeThread?.setThreadDelayMillis(1000)
            timeThread?.setLoadListener(this)
        }
        timeThread?.startThread()
    }

    override fun onLoading() {
        if (countdown <= 1){
            countdown = 9
            timeThread?.stopThread()
            showMullaLoading(isTOuchOut = false, isCancel = true)
            showMullaApplySuccess()
            return
        }
        countdown--
        showMullaTipsText()
    }

    /**
     * 设置文本
     */
    @SuppressLint("SetTextI18n")
    private fun showMullaTipsText(){
        binding.textCountdown.text = "${countdown}s"
        showMullaStepStatusView()
    }

    /**
     * 贷款订单创建成功
     */
    private fun showMullaApplySuccess(){
        launch(Dispatchers.Main){
            delay(1000)
            //通知刷新总流程
            MyApp.app.publisher.publish(KeurEventData(KeurEventData.TYPE.KEUR_PROCESS_REFRESH))
            hideMullaLoading()
            //返回首页
            finish()
        }
    }

    /**
     * 显示状态
     */
    private fun showMullaStepStatusView(){
        if (countdown in 7..9){
            binding.imgStep1.setImageResource(R.mipmap.mulla_wait_step2_icon)
            binding.vStep1Bottom.setBackgroundColor(Color.parseColor("#FFBBBBBB"))

            binding.vStep2Top.setBackgroundColor(Color.parseColor("#FFBBBBBB"))
            binding.imgStep2.setImageResource(R.mipmap.mulla_wait_step3_icon)
            binding.vStep2Bottom.setBackgroundColor(Color.parseColor("#FFBBBBBB"))

            binding.vStep3Top.setBackgroundColor(Color.parseColor("#FFBBBBBB"))
            binding.imgStep3.setImageResource(R.mipmap.mulla_wait_step3_icon)
            return
        }

        if (countdown in 4..6){
            binding.imgStep1.setImageResource(R.mipmap.mulla_wait_step1_icon)
            binding.vStep1Bottom.setBackgroundColor(Color.parseColor("#FF4DB673"))

            binding.vStep2Top.setBackgroundColor(Color.parseColor("#FF4DB673"))
            binding.imgStep2.setImageResource(R.mipmap.mulla_wait_step2_icon)
            binding.vStep2Bottom.setBackgroundColor(Color.parseColor("#FFBBBBBB"))

            binding.vStep3Top.setBackgroundColor(Color.parseColor("#FFBBBBBB"))
            binding.imgStep3.setImageResource(R.mipmap.mulla_wait_step3_icon)
            return
        }
        binding.imgStep1.setImageResource(R.mipmap.mulla_wait_step1_icon)
        binding.vStep1Bottom.setBackgroundColor(Color.parseColor("#FF4DB673"))

        binding.vStep2Top.setBackgroundColor(Color.parseColor("#FF4DB673"))
        binding.imgStep2.setImageResource(R.mipmap.mulla_wait_step1_icon)
        binding.vStep2Bottom.setBackgroundColor(Color.parseColor("#FF4DB673"))

        binding.vStep3Top.setBackgroundColor(Color.parseColor("#FF4DB673"))
        binding.imgStep3.setImageResource(R.mipmap.mulla_wait_step2_icon)
    }

    /**
     * 获取查看的产品名称
     */
    fun loadProductName(): String {
        return intent.extras?.getString(INTENT_KEY_PRODUCT).toString()
    }

    /**
     * 获取查看的产品Token
     */
    fun loadProductToken(): String {
        return intent.extras?.getString(INTENT_KEY_TOKEN).toString()
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addKeurEventAction(KeurEventType.PAGE.KEUR_PAGE_APPLY_WAIT_PREVIEW_START, "")
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addKeurEventAction(KeurEventType.PAGE.KEUR_PAGE_APPLY_WAIT_PREVIEW_END, "")
        if (timeThread != null) {
            timeThread?.stopThread()
            timeThread = null
        }
    }
}